using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Acms.AcmsControls
{
    public class TemplateLoaderControl : WebControl, INamingContainer
    {
        protected override void  OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CurrentTemplateControl.AcmsContext = ((TemplatePage)Page).AcmsContext;
            }
            base.OnLoad(e);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            TemplatePage templatePage = this.Page as TemplatePage;
            if(templatePage != null)
            {
                TemplateUserControl ctrl = Page.LoadControl(templatePage.AcmsContext.TemplatePath) as TemplateUserControl;
                if (ctrl != null)
                {
                    this.Controls.Add(ctrl);
                }
                else
                {
                    throw new ApplicationException(string.Format("'{0}' could not be found or did not inherit from TemplateUserControl", templatePage.AcmsContext.TemplatePath));
                }
            }
            else
            {
                throw new ApplicationException(string.Format("Page must inherit from TemplatePage"));
            }
        }

        private TemplateUserControl CurrentTemplateControl
        {
            get 
            {
                EnsureChildControls();
                return this.Controls[0] as TemplateUserControl;
            }
        }
    }
}
